﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Criterion;
using NhJump.Persistence.Context;
using NhJump.Persistence.Querying.Definition;
using NhJump.Persistence.Querying.Executable;
using NhJump.Persistence.Wcf.Autofac.Model;

namespace NhJump.Persistence.Wcf.Autofac.Repositories
{
    public interface ICustomerRepository
    {
        void SaveOrUpdate(Customer entity);
        void AttachUnchanged(Customer persistent);
        void Delete(Customer forDeletion);
        IExecutableQuery<Customer, int> ById(int id);
        IExecutableQuery<Customer, int> PrepareQuery(IQueryDefinition<Customer, int> queryDefinition);
        IList<Customer> Execute(QueryOver<Customer, Customer> queryOver);
        IList<Customer> GetAll();
        Customer Get(int id);
        void DeleteCustomerByName(string name);
        IList<Customer> GetCustomersByName(string name);
    }

    public class CustomerRepository : NHibernateRepository<Customer, int>, ICustomerRepository
    {
        public CustomerRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }

        public CustomerRepository()
        {
        }

        public void DeleteCustomerByName(string name)
        {
            var customers = GetCustomersByName(name);

            if (!customers.Any()) throw new Exception("Customer not found");

            foreach (var customer in customers)
            {
                Delete(customer);
            }
        }

        public IList<Customer> GetCustomersByName(string name)
        {
            var queryOver =
                QueryOver.Of<Customer>()
                    .Where(e => e.Name == name);

            var customers = Execute(queryOver);

            return customers;
        }
    }
}